package com.bt.lms.ui.page.teaching.plan;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.TeachingPlanBizTypeConstant;
import com.bt.lms.entity.TeachingPlanBasicInfo;
import com.bt.lms.entity.page.Page;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.ui.action.teaching.plan.*;
import com.bt.lms.ui.action.teaching.plan.query.LastLabAction;
import com.bt.lms.ui.action.teaching.plan.query.FirstLabAction;
import com.bt.lms.ui.action.teaching.plan.query.UnbindPackage;
import com.bt.lms.ui.page.sys.style.LabStyle;
import com.bt.lms.ui.page.sys.utils.MyButton;
import com.bt.lms.ui.page.sys.utils.MyLabel;
import com.bt.lms.ui.vo.teachingplan.TeachingPlanVo;
import com.bt.lms.main.BotLmsApp;
import com.bt.lms.ui.page.sys.style.BtnStyle;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;


/**
 * 教学计划信息界面
 */
public class PageTeachingPlanBasicInfoList extends VBox {


    public TableView tableView;

    /**
     * 高
     */
    public Integer height = 800;


    /**
     * 教学计划
     */
    public PageTeachingPlanBasicInfoList() {

        //初始化所在位置
        initLocation();

        this.setPrefWidth(BotLmsApp.PER_WIGHT);
        this.setPrefHeight(height);

        initPagingConditionQuery();

        initAddTeachingPlanButton();

        initTable();

        Page<TeachingPlanBasicInfo> teachingPlanBasicInfoPage = new Page<>();

        //初始化表格数据
        Integer current = initTableView();
        //初始化分页
        initQuery(teachingPlanBasicInfoPage,current);



        //设置内间距
        Insets insets = new Insets(10);
        this.setPadding(insets);

    }

    /**
     * 初始化列表
     */
    public Integer initTableView() {

        //1、组包
        Page page = new Page();
        String jsonStr = JSON.toJSONString(page);
        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType(TeachingPlanBizTypeConstant.PLAN_QUERY);
        reqMsg.setData(jsonStr);
        byte[] msgByte = reqMsg.toBytes();

        //2、组网
        String serverip = "127.0.0.1";
        int port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(serverip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //3、发送消息
        OutputStream out = null;
        try {
            out = socket.getOutputStream();
            out.write(msgByte);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //4、接收消息
        byte[] acceptBuffer = new byte[2100];
        try {
            InputStream in = socket.getInputStream();
            in.read(acceptBuffer);
            in.close();
            out.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        UnbindPackage unbindP = new UnbindPackage();
        Integer current = unbindP.unbindPackage(acceptBuffer, tableView);

        return current;

        //解包
//        RespMsg respMsg = RespMsg.toRespMsg(acceptBuffer);
//        String data = respMsg.getData();//获取数据
//        page = JSONObject.parseObject(data, Page.class);//处理数据
//        List records = page.getRecords();//分页里的集合
//        List<TeachingPlanBasicInfo> teachingPlanBasicInfos = new ArrayList<>();//新的集合
//
//        for (int i = 0; i < records.size(); i++) {
//
//            Object teachingInfo = records.get(i);
//            String teachingInfoStr = teachingInfo.toString();
//            TeachingPlanBasicInfo teachingPlanBasicInfo = JSONObject.parseObject(teachingInfoStr, TeachingPlanBasicInfo.class);
//            teachingPlanBasicInfos.add(teachingPlanBasicInfo);
//
//        }
//
//        //处理集合里的数据
//        List<TeachingPlanVo> teachingPlanVos = new ArrayList<>();
//
//
//        for (int i = 0; i < teachingPlanBasicInfos.size(); i++) {
//
//            TeachingPlanBasicInfo teachingPlanBasicInfo = teachingPlanBasicInfos.get(i);
//
//            String code = teachingPlanBasicInfo.getCode();//计划编号
//
//            String name = teachingPlanBasicInfo.getName();//教学计划名称
//
//            Integer learningCenterI = teachingPlanBasicInfo.getLearningCenter();//所属的学习中心
//            String learningCenter = null;
//            switch (learningCenterI) {
//
//                case 2:
//                    learningCenter = "北京师范大学";
//                    break;
//                case 1:
//                    learningCenter = "北京大学";
//                    break;
//            }
//
//            Major majorInfo = teachingPlanBasicInfo.getMajorInfo();//所属专业
//
//
//            Integer applyLevel = teachingPlanBasicInfo.getApplyLevel();//适用层次
//            String applyLevelStr = null;
//            switch (applyLevel) {
//                case 1:
//                    applyLevelStr = "高中";
//                    break;
//                case 2:
//                    applyLevelStr = "大专";
//                    break;
//                case 3:
//                    applyLevelStr = "本科";
//                    break;
//            }
//
//            Integer lengthOfSchoolingText = teachingPlanBasicInfo.getLengthOfSchoolingText();//学制文本
//            String lengthOfSchoolingTStr = lengthOfSchoolingText.toString();
//
//            Integer lengthOfSchooling = teachingPlanBasicInfo.getLengthOfSchooling();//学制单位
//            String lengthOfSchoolingStr = null;
//            switch (lengthOfSchooling) {
//                case 1:
//                    lengthOfSchoolingStr = "年";
//                    break;
//                case 2:
//                    lengthOfSchoolingStr = "月";
//                    break;
//                case 3:
//                    lengthOfSchoolingStr = "学时";
//                    break;
//            }
//            String lengthOfSchoolingT = lengthOfSchoolingTStr + lengthOfSchoolingStr;//学制
//
//            Integer statusI = teachingPlanBasicInfo.getStatus();//状态
//            String status = null;
//            switch (statusI) {
//                case 1:
//                    status = "草稿";
//                    break;
//                case 2:
//                    status = "已启用";
//                    break;
//                case 3:
//                    status = "已完成";
//                    break;
//            }
//
//            Integer relCourseQuantity = teachingPlanBasicInfo.getRelCourseQuantity();//关联课程数
//
//            String currentTerm = teachingPlanBasicInfo.getCurrentTerm();//等前学期
//
//            HBox operationHBox = new HBox();
//            operationHBox.setSpacing(10);
//            if (status.equals("草稿")) {
//
//                Button enableBtn = new Button("启用");
//                enableBtn.setCursor(Cursor.HAND);
//                Button editBtn = new Button("编辑");
//                editBtn.setCursor(Cursor.HAND);
//                Button deleteBtn = new Button("删除");
//                deleteBtn.setCursor(Cursor.HAND);
//                Button addCourseBtn = new Button("新增关联课程");
//                addCourseBtn.setCursor(Cursor.HAND);
//                operationHBox.getChildren().addAll(enableBtn, editBtn, deleteBtn, addCourseBtn);
//            } else if (status.equals("已启用")) {
//                Button confirmCompletionBtn = new Button("确认完成");
//                confirmCompletionBtn.setCursor(Cursor.HAND);
//                operationHBox.getChildren().add(confirmCompletionBtn);
//            }
//            CheckBox checkBox = new CheckBox();
//            TeachingPlanVo teachingPlanVo = new TeachingPlanVo(checkBox, code, name, learningCenter, "", applyLevelStr, lengthOfSchoolingT, status, relCourseQuantity, currentTerm, operationHBox);
//            teachingPlanVos.add(teachingPlanVo);
//        }
//
//
//        //将教学计划数据集合转换成Javafx组件集合
//        ObservableList<TeachingPlanVo> teachingPlanBasicInfos1 = FXCollections.observableArrayList(teachingPlanVos);
//        //把数据放入表格当中
//        tableView.setItems(teachingPlanBasicInfos1);
    }


    /**
     * 初始化所在位置
     */
    public void initLocation() {

        HBox hBox = new HBox();
        Insets insets = new Insets(10);
        hBox.setPadding(insets);
        Label label = new Label("当前位置：🏠>教学管理>教学计划");
        Font font = Font.font("仿宋", FontWeight.THIN, FontPosture.REGULAR, 18);
        label.setFont(font);
        hBox.getChildren().add(label);
        this.getChildren().add(hBox);

    }

    /**
     * 初始化分页条件查询
     */
    public void initPagingConditionQuery() {

        //盒子
        VBox vBox = new VBox();
        Insets insets = new Insets(10);
        vBox.setPadding(insets);
        vBox.setSpacing(10);

        HBox topHBox = new HBox();
        topHBox.setSpacing(10);

        HBox bottomHBox = new HBox();
        bottomHBox.setSpacing(10);

        ObservableList<Node> children = vBox.getChildren();
        children.addAll(topHBox, bottomHBox);
        //标签和下拉框和文本框
        Label belongToCollegeLabel = new Label("选择所属的学习中心:");

        ComboBox<String> belongToCollegeComboBox = new ComboBox<>();
        belongToCollegeComboBox.setCursor(Cursor.HAND);
        belongToCollegeComboBox.getSelectionModel().select("清华大学");
        belongToCollegeComboBox.getItems().add("清华大学");
        belongToCollegeComboBox.getItems().add("北京师范大学");
        belongToCollegeComboBox.getItems().add("山西理工大学");
        belongToCollegeComboBox.getItems().add("麻省理工大学");

        //适合层次
        Label applyLevelLabel = new Label("适合层次:");

        ComboBox<String> applyLevelComboBox = new ComboBox<>();
        applyLevelComboBox.setCursor(Cursor.HAND);
        applyLevelComboBox.getSelectionModel().select("免费师范生");
        applyLevelComboBox.getItems().add("免费师范生");
        applyLevelComboBox.getItems().add("免费师范生硕士");
        applyLevelComboBox.getItems().add("职后教育");
        applyLevelComboBox.getItems().add("其他");

        //选择专业
        Label belongToMajorLabel = new Label("选择专业:");

        ComboBox<String> belongToMajorComboBox = new ComboBox<>();
        belongToMajorComboBox.setCursor(Cursor.HAND);
        belongToMajorComboBox.getSelectionModel().select("java");
        belongToMajorComboBox.getItems().add("java");
        belongToMajorComboBox.getItems().add("c语言");
        belongToMajorComboBox.getItems().add("c++语言");

        //状态
        Label teachingPlanStateLabel = new Label("状态:");

        ComboBox<String> teachingPlanStateComboBox = new ComboBox<>();
        teachingPlanStateComboBox.setCursor(Cursor.HAND);
        teachingPlanStateComboBox.getSelectionModel().select("状态");
        teachingPlanStateComboBox.getItems().add("编辑中");
        teachingPlanStateComboBox.getItems().add("启用中");
        teachingPlanStateComboBox.getItems().add("已完成");

        //搜索框
        Label teachingPlanSerialLabel = new Label("教学计划名称:");

        TextField teachingPlanSerialTF = new TextField();
        teachingPlanSerialTF.setPromptText("输入教学计划名称");

        //搜索按钮
        Button searchBtn = new Button("搜索");
        searchBtn.setCursor(Cursor.HAND);

        //放盒子里
        ObservableList<Node> children1 = topHBox.getChildren();
        children1.addAll(belongToCollegeLabel, belongToCollegeComboBox, applyLevelLabel, applyLevelComboBox, belongToMajorLabel
                , belongToMajorComboBox);

        ObservableList<Node> children2 = bottomHBox.getChildren();
        children2.addAll(teachingPlanStateLabel, teachingPlanStateComboBox, teachingPlanSerialLabel, teachingPlanSerialTF,
                searchBtn);

        //放入主盒子
        ObservableList<Node> children3 = this.getChildren();
        children3.add(vBox);

    }

    /**
     * 初始化新增教学计划按钮
     */
    public void initAddTeachingPlanButton() {

        //盒子
        HBox hBox = new HBox();
        hBox.setSpacing(10);
        //内间距
        Insets insets = new Insets(10);
        hBox.setPadding(insets);
        //新增教学计划按钮
        Button addTeachingPlanButton = new Button("新增教学计划");
        addTeachingPlanButton.setCursor(Cursor.HAND);
        BtnStyle.addBtn(addTeachingPlanButton);
        LAddTeachingPlanButtonAction addTeachingPlanButtonAction = new LAddTeachingPlanButtonAction(this);
        addTeachingPlanButton.setOnAction(addTeachingPlanButtonAction);
        //按钮放到盒子
        ObservableList<Node> children = hBox.getChildren();
        children.add(addTeachingPlanButton);
        ObservableList<Node> children1 = this.getChildren();
        children1.add(hBox);

    }

    /**
     * 教学计划表
     */
    public void initTable() {

        //创建表格组件
        tableView = new TableView();
        tableView.setEditable(true);


        //创建列头
        TableColumn<TeachingPlanVo, Integer> checkBoxCol = new TableColumn();//多选框
        TableColumn<TeachingPlanVo, Integer> codeCol = new TableColumn<>("计划编号");
        codeCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.04);
        TableColumn<TeachingPlanVo, String> nameCol = new TableColumn<>("教学计划名称");
        nameCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.12);
        TableColumn<TeachingPlanVo, String> learningCenterCol = new TableColumn<>("所属的学习中心");
        learningCenterCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.052);
        TableColumn<TeachingPlanVo, String> belongToMajorCol = new TableColumn<>("所属专业");
        belongToMajorCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.05);
        TableColumn<TeachingPlanVo, String> applyLevelCol = new TableColumn<>("适用层次");
        applyLevelCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.08);
        TableColumn<TeachingPlanVo, String> lengthOfSchoolingCol = new TableColumn<>("学制");
        lengthOfSchoolingCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.06);
        TableColumn<TeachingPlanVo, String> statusCol = new TableColumn<>("状态");
        statusCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.05);
        TableColumn<TeachingPlanVo, String> relevanceCourseQuantityCol = new TableColumn<>("关联课程数");
        relevanceCourseQuantityCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.1);
        TableColumn<TeachingPlanVo, String> currentTermCol = new TableColumn<>("当前学期");
        currentTermCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.05);
        TableColumn<TeachingPlanVo, String> operationCol = new TableColumn("操作");
        operationCol.setMinWidth(BotLmsApp.PER_WIGHT * 0.22);
        //把列头放入表内
        ObservableList columns = tableView.getColumns();
        columns.addAll(checkBoxCol, codeCol, nameCol, learningCenterCol, belongToMajorCol, applyLevelCol,
                lengthOfSchoolingCol, statusCol, relevanceCourseQuantityCol, currentTermCol, operationCol);

        //表里加盒子
        CheckBox checkBox0 = new CheckBox();
        checkBox0.setCursor(Cursor.HAND);
        CheckBox checkBox1 = new CheckBox();
        checkBox1.setCursor(Cursor.HAND);
        CheckBox checkBox2 = new CheckBox();
        checkBox2.setCursor(Cursor.HAND);

        //配置列映射，让每一列知道要展示的属性是哪一个
        checkBoxCol.setCellValueFactory(new PropertyValueFactory<>("checkBox"));
        codeCol.setCellValueFactory(new PropertyValueFactory<>("code"));
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
        learningCenterCol.setCellValueFactory(new PropertyValueFactory<>("learningCenter"));
        belongToMajorCol.setCellValueFactory(new PropertyValueFactory<>("belongToMajor"));
        applyLevelCol.setCellValueFactory(new PropertyValueFactory<>("applyLevel"));
        lengthOfSchoolingCol.setCellValueFactory(new PropertyValueFactory<>("lengthOfSchooling"));
        statusCol.setCellValueFactory(new PropertyValueFactory<>("status"));
        relevanceCourseQuantityCol.setCellValueFactory(new PropertyValueFactory<>("relevanceCourseQuantity"));
        currentTermCol.setCellValueFactory(new PropertyValueFactory<>("currentTerm"));
        operationCol.setCellValueFactory(new PropertyValueFactory<>("operation"));

//        //自定义列格式
//        nameCol.setCellFactory(new Callback<TableColumn<TeachingPlanVo, String>, TableCell<TeachingPlanVo, String>>() {
//            @Override
//            public TableCell<TeachingPlanVo, String> call(TableColumn<TeachingPlanVo, String> param) {
//                return new TableCell<TeachingPlanVo, String>(){
//                    @Override
//                    protected void updateItem(String item, boolean empty) {
//                        super.updateItem(item, empty);
//
//                        if (item !=null){
//                            setGraphic(new Label(item));
//                        }
//
//
//                    }
//                };
//            }
//        });

        //把表放到盒子里
        ObservableList<Node> children = this.getChildren();
        children.add(tableView);


    }

    /**
     * 初始化分页
     */
    public void initQuery(Page<TeachingPlanBasicInfo> page, Integer current) {

        //数据控制
        int width = 45;
        Integer sumStrip = 100;//总条数
        int present = 10;//当前页数
        String presentStr = "/" + present;

        //初始化分页的盒子
        HBox queryHBox = new HBox();
        Insets insets = new Insets(10);
        queryHBox.setPadding(insets);
        queryHBox.setAlignment(Pos.CENTER_RIGHT);
        queryHBox.setSpacing(10);
        this.getChildren().add(queryHBox);

        Page<TeachingPlanBasicInfo> teachingPage = new Page<>();
        Integer size = teachingPage.getSize();


        //组件
        MyLabel firstLab = new MyLabel("« 首页");
        queryHBox.getChildren().add(firstLab);
        //样式
        LabStyle.paging(firstLab);
        //事件
//        UnbindPackage unbindPackage = new UnbindPackage();
//        Integer current = unbindPackage.current;
//        Integer current = page.getCurrent();

        FirstLabAction firstLabAction = new FirstLabAction(tableView, current);
        firstLab.setOnMouseClicked(firstLabAction);

        MyLabel lastLab = new MyLabel("« 上一页");
        queryHBox.getChildren().add(lastLab);
        //样式
        LabStyle.paging(lastLab);
        //事件
        UnbindPackage unbindP = new UnbindPackage();
        Integer current1 = unbindP.current;
//        FirstLabAction firstLabActionLastLab = new FirstLabAction(tableView, current);
//        lastLab.setOnMouseClicked(firstLabActionLastLab);
        LastLabAction currentTeachingAction = new LastLabAction(tableView,current);
        lastLab.setOnMouseClicked(currentTeachingAction);


        MyButton pageOne = new MyButton("1");
        queryHBox.getChildren().add(pageOne);
        //样式
        BtnStyle.pagingCurrent(pageOne);
        //事件
        FirstLabAction pageOneFirstLabAction = new FirstLabAction(tableView, (current = (new Page<>().getCurrent())));
        pageOne.setOnMouseClicked(pageOneFirstLabAction);

        MyButton pageTwo = new MyButton("2");
        queryHBox.getChildren().add(pageTwo);
        //样式
        BtnStyle.paging(pageTwo);
        //事件
        FirstLabAction pageTwoFirstLabAction = new FirstLabAction(tableView, (current = (Integer.parseInt(pageOne.getText())) + 1));
        pageTwo.setOnMouseClicked(pageTwoFirstLabAction);

        MyButton pageThree = new MyButton("3");
        queryHBox.getChildren().add(pageThree);
        //样式
        BtnStyle.paging(pageThree);
        //事件
        FirstLabAction pageThreeFirstLabAction = new FirstLabAction(tableView, current = 3);
        pageThree.setOnMouseClicked(pageThreeFirstLabAction);

        MyLabel nextLab = new MyLabel("下一页 »");
        queryHBox.getChildren().add(nextLab);
        //样式
        LabStyle.paging(nextLab);
        //事件
        LabStyle.pagingAction(nextLab);

        MyLabel finallyLab = new MyLabel("尾页 »");
        queryHBox.getChildren().add(finallyLab);
        //样式
        LabStyle.paging(finallyLab);
        //事件
        LabStyle.pagingAction(finallyLab);

        //条数统计
        Label explainLab = new Label("总记录数");
        queryHBox.getChildren().add(explainLab);

        Label sumLab = new Label(sumStrip + "");
        queryHBox.getChildren().add(sumLab);
        //样式
        LabStyle.status(sumLab, LabStyle.STOP);

        Label unitLab = new Label("条");
        queryHBox.getChildren().add(unitLab);

        //跳转框
        TextField pageNumberTF = new TextField();
        pageNumberTF.setPrefWidth(width);
        queryHBox.getChildren().add(pageNumberTF);

        //当前页标签
        Label presentLab = new Label(presentStr);
        queryHBox.getChildren().add(presentLab);

        //跳转按钮
        MyButton notarizeBtn = new MyButton("GO");
        queryHBox.getChildren().add(notarizeBtn);


    }


}
